﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Generic;
using Com.Library.DB.Manager;
using Com.Library.Cookie;
using Com.Framework.Cookie;

namespace Com.Web.coffinegurunaru.manager
{
    public partial class login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
			InitializeFirstManager();

            if (this.IsPostBack)
            {
				string redirectUrl = Request["redirect"];
				string UserID = Request.Form["txtLoginID"].ToString();
				string UserPWD = Request.Form["txtPWD"].ToString();

				if (ManagerModel.VerifyPassword(UserID, UserPWD))
				{
					ManagerEntity manager = ManagerModel.GetInfo(null, UserID);
					CookieParam param = new CookieParam();
					string cookieString = string.Format("ManagerSN={0},ManagerID={1},ManagerName={2}", manager.n4ManagerSN, manager.strManagerID, manager.strManagerName);

					ManagerCookie cookie = new ManagerCookie();
					cookie.SetEncCookie("MSC", cookieString);

					if (!string.IsNullOrEmpty(redirectUrl))
					{
						ClientScript.RegisterStartupScript(this.GetType(), "loginok", "location.href=\"" + redirectUrl + "\"", true);
						return;
					}
					else
					{
						ClientScript.RegisterStartupScript(this.GetType(), "loginok", "location.href=\"/manager/user/user.aspx\"", true);
						return;
					}
				}
            }
        }

		// 계정이 아예 없는 경우 첫번째 계정을 생성한다.
		private void InitializeFirstManager()
		{
			int cntRow = 0;
			int cntTotal = 0;
			ManagerModel.GetList(1, 0, out cntRow, out cntTotal);

			if (cntTotal == 0)
			{
				ManagerModel.Create("coffine", "zhvls!12", "메인매니저");
			}
		}
    }
}
